//
//  HLCreateNoteController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/13.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLCreateNoteController.h"
#import "WRNavigationBar.h"
#import <ReactiveObjC/ReactiveObjC.h>
#import "HLLoginTextFiled.h"
#import "HLPlaceHolderTextView.h"
#import "MBProgressHUD+HL.h"
#import "HttpRequestManager.h"
#import "HLUserInfo.h"

@interface HLCreateNoteController ()<UITextViewDelegate>

/** 发布按钮  */
@property (nonatomic ,strong) UIButton *publishButton;

/** 问题  */
@property (nonatomic ,strong) HLPlaceHolderTextView *contentTextView;

@end

@implementation HLCreateNoteController

- (UIButton *)publishButton
{
    if (!_publishButton) {
        _publishButton = [[UIButton alloc] init];
        _publishButton.enabled = NO;
        [_publishButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
        [_publishButton setTitleColor:kColorMineBlueBG forState:UIControlStateNormal];
        [_publishButton setTitle:@"保存" forState:UIControlStateNormal];
        [_publishButton addTarget:self action:@selector(publishButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [_publishButton sizeToFit];
    }
    return _publishButton;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [UIColor wr_setDefaultNavBarBarTintColor:[UIColor whiteColor]];
    [UIColor wr_setDefaultNavBarTitleColor:HLRGB(30, 30, 30)];
    [UIColor wr_setDefaultNavBarTintColor:HLRGB(30, 30, 30)];
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSForegroundColorAttributeName:HLRGB(30, 30, 30)}];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [UIColor wr_setDefaultNavBarBarTintColor:kColorNavBG];
    [UIColor wr_setDefaultNavBarTintColor:[UIColor whiteColor]];
    [UIColor wr_setDefaultNavBarTitleColor:[UIColor whiteColor]];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setNavItem];
    
    [self setUI];
    
    RAC(_publishButton,enabled) = [RACSignal combineLatest:@[_contentTextView.rac_textSignal] reduce:^id _Nullable(NSString *content){
        return @( content.length > 0 );
    }];
    
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return  UIStatusBarStyleDefault;
}

- (void)setNavItem
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemClick)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.publishButton];
    self.view.backgroundColor = HLRGB(245,245, 245);
}

- (void)setUI
{

    self.automaticallyAdjustsScrollViewInsets = NO;
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(10, 74, ScreenWidth-20, 0.4* ScreenWidth  -  10)];
    [self.view addSubview:contentView];
    
    self.contentTextView = [[HLPlaceHolderTextView alloc] initWithFrame:CGRectMake(10, 0, ScreenWidth-40, 0.4* ScreenWidth  -  10)];
    self.contentTextView.text = self.note;
    self.contentTextView.font = [UIFont systemFontOfSize:16];
    self.contentTextView.backgroundColor = [UIColor clearColor];
    self.contentTextView.placeholder =  @"输入笔记......" ;
    self.contentTextView.placeholderColor = HLRGB(30, 30, 30);
    [contentView addSubview:self.contentTextView];
    [self.contentTextView becomeFirstResponder];
}

- (void)publishButtonClick
{
    if([self.title isEqualToString:@"编辑笔记"]){
        [self editNoteRequest];
        return;
    }
    if([self.title isEqualToString:@"创建笔记"]){
        [self createNoteRequest];
    }
}

- (void)createNoteRequest
{
    [MBProgressHUD show];
    __weak typeof(self) weakSelf = self;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestAddNotes signStr];
    params[@"course_id"] = self.note_course_id;
    params[@"user_id"] = [HLUserInfo account].userid;
    params[@"content"] = [self switchStringEncode:self.contentTextView.text];
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestAddNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            [MBProgressHUD showSuccessMessage:@"笔记创建成功"];
            
            [weakSelf leftItemClick];
            if(self.noteCompletionBlock){
                self.noteCompletionBlock(self.contentTextView.text);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];
}


- (void)editNoteRequest
{
    [MBProgressHUD show];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"sign"] = [kHLRequestEditNotes signStr];
    params[@"course_id"] = self.note_course_id;
    params[@"type"] = @"1";
    params[@"content"] = [self switchStringEncode:self.contentTextView.text];
    params[@"user_id"] = [HLUserInfo account].userid;
    __weak typeof(self) weakSelf = self;
    [[HTTPRequestManager defaultManager] HTTPGetRequestWithApiName:kHLRequestEditNotes parameters:params success:^(NSURLSessionDataTask * _Nonnull dataTask, id  _Nonnull responseObject){
        [MBProgressHUD hideHUD];
        if ([responseObject[@"code"] integerValue] == 200) {
            if ([responseObject[@"state"] isEqualToString:@"1"]) {
                [MBProgressHUD showSuccessMessage:@"编辑成功"];
    
                [weakSelf leftItemClick];
                if(self.noteCompletionBlock){
                    self.noteCompletionBlock(self.contentTextView.text);
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nonnull dataTask, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showErrorMessage:@"网络超时"];
    }];

}


- (NSString *)switchStringEncode:(NSString *)str
{
     /**** 表情字符 适配  转换发送到服务器,请求下来再转换回来  ****/
//    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    return str;
}

- (void)leftItemClick
{
    [self.contentTextView resignFirstResponder];
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}


@end
